package com.ncmem.up6.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

import org.apache.commons.lang.StringUtils;

public class PathTool {
	
	/**
	 * 在linux中，getName()取出来的文件名称包含路径。需要手动去掉路径部分。
	 * @param n
	 * @return
	 */
	public static String getName(String n){
		File f = new File(n);
		String name = f.getName();
		int pos = name.lastIndexOf("\\");
		if(-1 == pos) pos = name.lastIndexOf("/");
		if(-1 == pos) return name;
		return name.substring(pos + 1);
	}

	public static String[] split(String str,String p)
	{
		List<String> arr = new ArrayList<String>();
		int posPre=0;
		int pos = str.indexOf(p);
		while(-1 != pos)
		{
			arr.add(str.substring(posPre,pos));
			posPre = pos+1;
			pos = str.indexOf(p, pos+1);
		}

		return arr.toArray(new String[0]);
	}
	
	public static String guid(){
		return UUID.randomUUID().toString().replace("-","");
	}

	public static String combin(String a,String b)
	{
		a = a.replace('\\', '/');
		b = b.replace('\\', '/');
		if (a.endsWith("/")) a = a.substring(0, a.length() - 1);
		if (b.startsWith("/")) b = b.substring(1);
		return a + "/" + b;
	}
	
	public static String getExtention(String n){
		String name = getName(n);

		int extIndex = name.lastIndexOf(".");
		//有扩展名
		if(-1 != extIndex)
		{
			String ext = name.substring(extIndex + 1);
			return ext;
		}
		return "";
	}
	
	public static Boolean exist(String v)
	{
		File f = new File(v);
		return f.exists();
	}
	
	public static boolean createDirectory(String v){

		File fd = new File(v);		
		//fix():不创建文件夹
		if(!fd.exists()) return fd.mkdirs();
		return true;
	}

	public static void mkdirsFromFile(String f)
	{
		String dir = getParent(f);
		PathTool.createDirectory(dir);
	}
	
	//规范化路径，与操作系统保持一致。
	public static String canonicalPath(String v) throws IOException{
		File f = new File(v);
		return f.getCanonicalPath();
	}
	
	public static String combine(String a,String b)
	{
		boolean split = a.endsWith("\\");
		if(!split) split = a.endsWith("/");
		if(b.startsWith("/")) b = b.substring(1);
		//没有斜杠
		if(!split)
		{
			return a.concat("/").concat(b);
		}//有斜框
		else{
			return a.concat(b);
		}		
	}
	
	public static String url_decode(String v)
	{
		v = v.replace("+","%20");	
		try {
			v = URLDecoder.decode(v,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//utf-8解码//客户端使用的是encodeURIComponent编码，
		return v;
	}

	/**
	 * 获取base64字符串并自动解码
	 * @param name
	 * @return
	 * @throws IOException
	 */
	public static String getBase64(String name) throws IOException {
		if(!StringUtils.isBlank(name))
		{
			String s = name.trim();
			byte[] buf = Base64.getDecoder().decode(s);
			s = new String(buf,"UTF-8");
			return s;

		}
		return "";
	}

	public static String url_safe_encode(String v)
	{
		try {
			v = URLEncoder.encode(v,"UTF-8");
			v = v.replace("+", "%20");
			v = v.replace("*", "%2A");
			v = v.replace("%7E", "~");
			v = v.replace("%2F", "/");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//utf-8解码//客户端使用的是encodeURIComponent编码，
		return v;
	}

	public static String getParent(String ps)
	{
		File f = new File(ps);
		return f.getParent();
	}

    /**
	 * 将相对路径转换成绝对路径
	 * @param ps res
	 * @return /up6/imgs
	 */
	public String MapPath(String ps)
	{		
		// /up6
		String root = this.getRoot();
		
		if(StringUtils.isBlank(ps)) return root;
		
		//传值： /imgs
		if(!StringUtils.equals("/", ps.substring(0, 1))) root.contains("/");

		root = PathTool.combine(root,ps);
		
		File f = new File(root);
		String path="";
		try {
			path = f.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return path;
	}

	/**
	 * 获取项目根目录
	 * @return C:\\java\\tomcat\\7.0.47\\webapps\\up6
	 */
	public String getRoot() 
	{
		//=>F:/jsp/springboot/up6/target/classes/
		String path = this.getClass().getResource("/").getPath();
		path = path.replaceAll("//", "/");

		if ( !StringUtils.isBlank(path) && !path.endsWith("/"))
		{
			path = path.concat("/");    //避免 WebLogic 和 WebSphere 不一致
		}

		//Windows=>删除开始的/
		if(System.getProperties().getProperty("os.name").indexOf("Windows")!=-1)
		{
			if(path.startsWith("/")) path = path.substring(1);
		}

		//打包模式
		if(path.startsWith("file:/"))
			path = path.substring("file:/".length());

		path = path.replace("%20", " ");//fix(2016-02-29):如果路径中包含空格,getPath会自动转换成%20

		//D:/app/tomcat/apache-tomcat-8.5.61/webapps/up6/WEB-INF/classes/
		int pos = path.indexOf("WEB-INF/classes/");
		if(pos != -1) path = path.substring(0,pos);
		return path;
	}

	
	public static String BytesToString(long byteCount)
	{
	    String[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
	    if (byteCount == 0)
	        return "0" + suf[0];
	    long bytes = Math.abs(byteCount);
	    int place = (new Double(Math.floor(Math.log(bytes) / Math.log(1024))).intValue());
	    double num = (double)bytes / Math.pow(1024, place);
	    num = new BigDecimal(num).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
	    return String.valueOf( (Math.signum(byteCount) * num) ) + suf[place];
	}
}